package com.wawayaya.bookreader.ViewPages;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.View;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.atomic.AtomicBoolean;
import wawayaya.kids_iread.R;
import com.wawayaya.bookreader.Imutualaction;
import com.wawayaya.bookreader.DefaultSettings;
import com.wawayaya.bookreader.bean.HotRegionData;
import com.wawayaya.bookreader.bean.Pagedata;
import com.wawayaya.util.Devicescreenbasicinfo;

public class NewContainerView extends FrameLayout {

	
	private Context m_ct = null;
	private Imutualaction m_callback = null;
	private NewBookPageView m_vbkg = null;
	private ImageView m_ivdummyprogress = null;
	private WebView m_wverrormsg = null;
	private float m_fratio = 1.0f;
	private int m_iratiodecode = 1;
	private float m_fdensity = 1.0f;
	private int m_inetid = 0;
	private int m_ibookid = 0;
	
    private Timer m_tmwaitloading = null;
	private TimerTask m_tmtaskwaitloading = null;
	private AtomicBoolean m_bdofree = new AtomicBoolean(false);
	private int m_waitanimres[] = null;
	private BitmapDrawable m_bdwaitanimref[] = null;
	private int m_iwaitanimframes = 0;
	private boolean m_bookdownloaderrorresolved = true;
	
	private int mBookOriginalW;
	private int mBookOriginalH;

    private int m_iviewXoffset = 0;
    private int m_iviewYoffset = 0;
    private RelativeLayout mContentLayout = null;

    private int mHotRegionIconWidth = 0;
    private int mHotRegionIconHeight = 0;
    private int mPageIndex = -1;


    private ArrayList<ImageButton> mHotRegionBtnList;
    private ArrayList<HotRegionData> mHotRegionDataList;
			
	public NewContainerView(Context context) {
		super(context);
		m_ct = context;
	}
	
	public NewContainerView(Context context, AttributeSet attrs) {
		super(context, attrs);
		m_ct = context;
	}
	
	public NewContainerView(Context context, AttributeSet attrs, int defStyle) {
		super(context, attrs, defStyle);
		m_ct = context;
	}
	
	public void setwaitanimresource(int[] iwaitanimresid, BitmapDrawable[] bdwaitanim) {
		m_waitanimres = iwaitanimresid;
		m_bdwaitanimref = bdwaitanim;
		m_iwaitanimframes = null != iwaitanimresid ? iwaitanimresid.length : 0;
	}
	
	public void setratio(float fratio, int idecoderatio, float fdensity, int orignalW, int orignalH, int iviewXoffet, int iviewYoffet) {
		m_fratio = fratio;
        m_iviewXoffset = iviewXoffet;
        m_iviewYoffset = iviewYoffet;

		m_iratiodecode = idecoderatio;
		m_fdensity = fdensity;
		
		mBookOriginalW = orignalW;
		mBookOriginalH = orignalH;
	}

	public void setbooknetid(int inetid) {
		m_inetid = inetid;
	}

	public void setbookid(int ibookid) {
		m_ibookid = ibookid;
	}
	
	public void setshowpinyinenglish(int istatus){
		if(null != m_vbkg) {
			m_vbkg.setShowPinyinAnotherLan(istatus);
		}
	}
		
	public void setposition(int position, Pagedata pd, int iviewXoffet, int iviewYoffet){

        mPageIndex = position;
		if(null != pd) {
			// the book part has been download and combined and parsed completely
			closewaitinnerpageloadingtext();
			m_vbkg.setinnerpage(position, pd, iviewXoffet, iviewYoffet);
		}
		else{
			showwaitinnerpageloadingtext();
			m_vbkg.waitinnerpageloading(position, iviewXoffet, iviewYoffet);
		}
	}
	
	public void setposition(int position, Pagedata pd, int iviewXoffet, int iviewYoffet, boolean bautokok){
        m_iviewXoffset = iviewXoffet;
        m_iviewYoffset = iviewYoffet;

        if(null != pd) {
			// the book part has been download and combined and parsed completely
			closewaitinnerpageloadingtext();
			m_vbkg.setinnerpage(position, pd, iviewXoffet, iviewYoffet, bautokok);
		}
		else{
			setposition(position, pd, iviewXoffet, iviewYoffet);
		}
	}
	
	public void setbookdownloaderrorresolved(boolean bookdownloaderrorresolved) {
		m_bookdownloaderrorresolved = bookdownloaderrorresolved;
		if(m_bookdownloaderrorresolved && null != m_wverrormsg) {
			m_wverrormsg.setVisibility(View.GONE);
		}
	}
	
	public void findviews(Imutualaction callback, int ikokcolor, Devicescreenbasicinfo dsi, int ireadtype, Pagedata pd){
		m_callback = callback;
        mContentLayout = (RelativeLayout)(findViewById(R.id.viewpage_container_content));
		m_vbkg = (NewBookPageView)(findViewById(R.id.bpv_pageradapterview));
		m_vbkg.setmutualactioncallback(callback, ikokcolor, dsi, ireadtype);
		m_vbkg.setbooknetid(m_inetid);
		m_vbkg.setbookid(m_ibookid);
		m_vbkg.setratio(m_fratio, m_iratiodecode, mBookOriginalW, mBookOriginalH);
        //m_vbkg.setParentLayout(this);
		m_ivdummyprogress = (ImageView)findViewById(R.id.iv_dummyprogress);
		m_wverrormsg = (WebView)findViewById(R.id.wv_errormsg);
		RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams)m_wverrormsg.getLayoutParams();
		if(null != rlp) {
			rlp.bottomMargin = (int)(DefaultSettings.BOTTOMMARGIN * m_fdensity * m_fratio);
			m_wverrormsg.setLayoutParams(rlp);
		}

        Drawable icon = m_ct.getResources().getDrawable(R.drawable.sread);
        mHotRegionIconWidth = icon.getIntrinsicWidth();
        mHotRegionIconHeight = icon.getIntrinsicHeight();
        int width = (int)(mHotRegionIconWidth * m_fratio);
        int height = (int)(mHotRegionIconHeight * m_fratio);
  /*      if (pd != null) {
            ArrayList<HotRegionData> hotregiondatalist = pd.getHotRegionData();
            if (hotregiondatalist != null && hotregiondatalist.size() > 0) {
                mHotRegionDataList = hotregiondatalist;
                for (int i = 0; i < hotregiondatalist.size(); i++) {
                    HotRegionData hotregion = hotregiondatalist.get(i);
                    if (hotregion != null) {
                        ImageButton button = new ImageButton(m_ct);
                        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(width, height);
                        lp.leftMargin = m_iviewXoffset + (int)((hotregion.mCenterX - width / 2)* m_fratio);
                        lp.topMargin = m_iviewYoffset + (int)((hotregion.mCenterY - height / 2) * m_fratio);
                        mContentLayout.addView(button, lp);
                        button.setBackground(null);
                        button.setImageResource(R.drawable.sread);
                        button.setTag(hotregion.mIndexes);
                        button.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Object indexs = v.getTag();
                                int[] indexslist = (int[])indexs;
                                m_vbkg.starthotkok(mPageIndex, indexslist);

                            }
                        });
                        if (mHotRegionBtnList == null) {
                            mHotRegionBtnList = new ArrayList<ImageButton>();
                        }
                        mHotRegionBtnList.add(button);
                    }
                }
            }
        }*/
	}
	
	public void tostopanim() {
		m_bdofree.set(true);
		closewaitinnerpageloadingtext();
	}
	
	public void recycle() {
		m_vbkg.recycle();
	}
	
	public NewBookPageView getbookapgeview() {
		return m_vbkg;
	}
	
	public void closewaitinnerpageloadingtext(){
    	m_ivdummyprogress.setVisibility(View.GONE);
    	closeanimtimer();
		if(null != m_ivdummyprogress) {
			m_ivdummyprogress.setBackgroundResource(0);
		}
	}
	
	public void recordselectedpage(boolean bselected) {
		if(null != m_vbkg) {
			m_vbkg.recordselectedpage(bselected);
		}
	}
	
	private void closeanimtimer() {
    	try{
			if(null != m_tmwaitloading) {
				m_tmwaitloading.cancel();
				m_tmwaitloading = null;
			}
			if(null != m_tmtaskwaitloading) {
				m_tmtaskwaitloading.cancel();
				m_tmtaskwaitloading = null;
			}
		}catch(Exception e){
		}
    	if(null != m_callback) {
    		m_callback.inwatingloadpagestatus(false);
    	}
	}
	
	private void showwaitinnerpageloadingtext(){
		m_callback.inwatingloadpagestatus(true);
		if(!m_bookdownloaderrorresolved) {
			closeanimtimer();
			showerrormessage();
			return;
		}
		if(0 == m_iwaitanimframes) {
			return;
		}
		m_tmwaitloading = new Timer();
		m_tmtaskwaitloading = new TimerTask()  {
    		int itimercount = 0;
			@Override
	        public void run(){
				if(m_bdofree.get()) {
					return;
				}
				if(null == m_bdwaitanimref){
					return;
				}
				else if(null == m_bdwaitanimref[itimercount]) {
					try{
						Bitmap bmp = BitmapFactory.decodeResource(m_ct.getResources(), m_waitanimres[itimercount]);
						m_bdwaitanimref[itimercount] = new BitmapDrawable(m_ct.getResources(), bmp);
					}catch(Exception e){
					}catch(OutOfMemoryError oe){
						m_bdwaitanimref[itimercount] = null;
					}
				}
				Message msg = new Message();
				msg.what = 0;
				msg.arg1 = itimercount;
				if(m_bdofree.get()) {
					return;
				}
				if(null != m_bdwaitanimref[itimercount]) {
					m_hshowwaittext.sendMessage(msg);
				}
				if(itimercount >= m_iwaitanimframes - 1) {
					itimercount = 0;
				}
				else{
					itimercount++;
				}
			}
	    };
	    m_tmwaitloading.schedule(m_tmtaskwaitloading, 0, 200);
	    m_ivdummyprogress.setVisibility(View.VISIBLE);
	}
	
	private Handler m_hshowwaittext = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			if(!m_bdofree.get()) {
				if(!m_bookdownloaderrorresolved) {
					closeanimtimer();
					showerrormessage();
					return;
				}
				try{
					if(null != m_bdwaitanimref[msg.arg1]) {
						m_ivdummyprogress.setBackgroundDrawable(m_bdwaitanimref[msg.arg1]);
					}
				}catch(Exception e){
				}
			}
		}
	};
	
	private void showerrormessage() {
		if(null != m_ivdummyprogress) {
			m_ivdummyprogress.setBackgroundDrawable(m_bdwaitanimref[1]);
			m_ivdummyprogress.setVisibility(View.VISIBLE);
		}
		String serror = this.getResources().getString(R.string.downloadError2);
		serror = "<p><font color=\"" + 
		DefaultSettings.PAGESELECTION_FOOTFONT_TOTALPAGE_COLORSHORT + "\" size=\"" +
				DefaultSettings.getscaledfontsize(DefaultSettings.FONTSIZE, m_fratio, m_fdensity) +
				"\">" + 
				serror + "</font></p>";
		m_wverrormsg.loadDataWithBaseURL(null, serror, "text/html", "UTF-8", null);	
		m_wverrormsg.setVisibility(View.VISIBLE);
	}
/*
    public void updataHotRegionButton(float ratio, int x_offset, int y_offset) {
        MyLog.d("HotRegion updataHotRegionButton " + ratio);
        if (mHotRegionBtnList != null && mHotRegionBtnList.size() > 0 && mHotRegionDataList != null && mHotRegionDataList.size() > 0
                && (mHotRegionBtnList.size() == mHotRegionDataList.size())) {
            int len = mHotRegionBtnList.size();
            for (int i = 0; i < len; i++) {
                RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams)mHotRegionBtnList.get(i).getLayoutParams();
                int width = (int)(mHotRegionIconWidth * ratio);
                int height = (int)(mHotRegionIconHeight * ratio);
                lp.width = width;
                lp.height = height;
                lp.leftMargin = x_offset + (int)((mHotRegionDataList.get(i).mCenterX - width / 2)* ratio);
                lp.topMargin = y_offset + (int)((mHotRegionDataList.get(i).mCenterY - height / 2) * ratio);
                mHotRegionBtnList.get(i).setLayoutParams(lp);
            }
        }
    }*/

}
